/**
 * Created by WebStorm.
 * User: Yxh
 * Date: 2016/6/19
 * Time: 13:12
 */

/**
 * 图片懒加载
 */
;(function ($, window, undefined) {

    var imgLoad = function (options) {

        this.settings = $.extend({}, imgLoad.defaults, options);

        this.init();
    };

    imgLoad.prototype = {

        /**
         * 初始化
         */
        init: function () {
            var that = this;

            $(that.settings.container).on("scroll", function () {
                that._update();
            });

            $(window).on("resize", function () {
                that._update();
            });

            this._update();
        },

        /**
         * 更新
         */
        update: function () {
            this._update(this);
        },

        /**
         * 滚动后更新
         */
        _update: function (that) {
            var that = this ;
            var elements = $(that.settings.elements.selector + "[" + that.settings.attrSrc + "]");

            elements.each(function (k, v) {
                var $self = $(v), imgSrc = $self.attr(that.settings.attrSrc);
                if (imgSrc && that.isShow(v, that.settings)) {
                    $self.removeAttr(that.settings.attrSrc);
                    $("<img />").one('load', function () {
                        var imgThat = this ;
                        if(that.settings.time){
                            setTimeout(function(){
                                $self.attr({'src' : imgSrc , "style" : that.updateStyle(v, imgThat, that.settings)}).fadeIn(that.settingsanimateTime);
                            } , that.settings.time);
                        }else{
                            $self.attr({'src' : imgSrc , "style" : that.updateStyle(v, imgThat, that.settings)}).fadeIn(that.settingsanimateTime);
                        }
                    }).one('error', function () {
                        var imgThat = this ;
                        imgThat.width = 376;
                        imgThat.height = 300;
                        if(that.settings.time){
                            setTimeout(function(){
                                $self.attr({'src': that.settings.errorImgSrc, "style" : that.updateStyle(v, imgThat, that.settings)}).fadeIn(that.settingsanimateTime);
                            } , that.settings.time);
                        }else{
                            $self.attr({'src': that.settings.errorImgSrc, "style" : that.updateStyle(v, imgThat, that.settings)}).fadeIn(that.settingsanimateTime);
                        }
                    }).attr("src", imgSrc);
                };
            });
        },

        /**
         * 判断当前图片是否在显示区域
         */
        isShow: function (element, setting) {
            var left = $(element).offset().left,
                top = $(element).offset().top,
                H = $(window).height(),
                W = $(window).width(),
                T = $(window).scrollTop(),
                L = $(window).scrollLeft(),
                isX = top >= T - setting.offsetH && top <= T + H + setting.offsetH,
                isY = left >= L - setting.offsetW && left <= L + W + setting.offsetW;
            return isX && isY;
        },

        /**
         * 修改图片style
         */
        updateStyle: function (self, that, settings) {
            var $self = $(self),
                $that = $(that),
                model = $that.attr("model") ? parseInt($that.attr("model")) : settings.model,
                style = '',
                pH = $self.parent().height(),
                pW = $self.parent().width(),
                h = that.height,
                w = that.width,

                status = w / h > pW / pH,
                comStyle = 'position:absolute;top:50%;left:50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);transform: translate(-50%, -50%);';
            if ($self.parent().css("position") == 'static') $self.parent().css({'position': 'relative'});

            if (model == 1) {
                $self.parent().css({'overflow': 'hidden'});
                style = (status ? 'height:100%;width:auto;' : 'height:auto;width:100%;') + comStyle;
            } else if (model == 2) {
                style = (!status ? 'height:100%;width:auto;' : 'height:auto;width:100%;') + comStyle;
            } else if (model == 3) {
                style = 'width:100%;height:auto;';
            }
            return style;
        }
    };

    /**
     * 默认配置
     */
    imgLoad.defaults = {

        //元素
        elements:'' ,

        //滚动条框
        container: window,

        //加载错误显示图片
        errorImgSrc: 'img/error.jpg',

        //默认模式 1 、图片自适应外框，显示图片中心位置。2、图片自适应外框、显示整个图片。3、图片宽度100%，高度自适应
        model: 1,

        //默认img标签真实地址属性
        attrSrc: 'img-src',

        //垂直距离多少开始显示
        offsetH: 200,

        //左右距离多少开始显示
        offsetW: 200,

        //延迟时间
        time : 0 ,

        //动画时间
        animateTime : 200
    };

    $.fn.imgLoad = function (options) {

        options = options ? options : {};

        options.elements = this;

        return new imgLoad(options);
    }

})(window.jQuery || window.Zepto, window);
